import 'package:bitcoin_mine/api/api.dart';
import 'package:bitcoin_mine/common/BaseEntity.dart';
import 'package:bitcoin_mine/common/global.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:get/get.dart';
import '../config/app_config.dart';
import '../http/http_request.dart';

class AuthService extends GetxService {
  static AuthService get to => Get.find();

  final GoogleSignIn _googleSignIn = GoogleSignIn(
    clientId: AppConfig.googleClientId,
  );

  @override
  void onInit() {
    super.onInit();
    print('认证服务已初始化');
  }

  /// 苹果登录
  Future<void> signInWithApple() async {
    try {
      // 检查苹果登录是否可用
      final isAvailable = await SignInWithApple.isAvailable();
      if (!isAvailable) {
        throw Exception('Apple Sign-In is not available on this device');
      }

      // 请求苹果登录
      final credential = await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );

      HttpRequest.instance.requestNetwork<BaseEntity<String>>(
        Api.appleLogin,
        method: "POST",
        params: {
          "user": credential.userIdentifier,
          "email": credential.email,
          "fullName": '${credential.givenName}+${credential.familyName}',
          "realUserStatus": '',
        },
        onSuccess: (value) {
          print('苹果绑定成功: $value');
          Global.updateMineInfo();
        },
        onError: (code, msg) {
          if (code == 401) {
            Global.resetToken(msg ?? '');
          } else {
            throw Exception(msg);
          }
        },
      );
    } catch (e) {
      print('苹果登录错误: $e');
    }
  }

  /// 谷歌登录
  Future<AuthResult> signInWithGoogle() async {
    try {
      // 触发谷歌登录流程
      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();

      if (googleUser == null) {
        return AuthResult(
          success: false,
          error: 'Google Sign-In was cancelled',
        );
      }

      // 获取认证详情
      await googleUser.authentication;

      // 模拟用户信息
      final userInfo = {
        'uid': 'google_${DateTime.now().millisecondsSinceEpoch}',
        'email': googleUser.email,
        'displayName': googleUser.displayName ?? 'Google User',
        'provider': 'google',
        'photoURL': googleUser.photoUrl,
      };

      return AuthResult(
        success: true,
        user: userInfo,
        provider: 'google',
        displayName: googleUser.displayName ?? 'Google User',
        email: googleUser.email,
      );
    } catch (e) {
      print('谷歌登录错误: $e');
      return AuthResult(success: false, error: e.toString());
    }
  }

  /// 登出
  Future<void> signOut() async {
    try {
      await _googleSignIn.signOut();
    } catch (e) {
      print('登出错误: $e');
    }
  }

  /// 解绑Google账号
  Future<void> unbindGoogle() async {
    try {
      await _googleSignIn.signOut();
    } catch (e) {
      print('解绑Google账号错误: $e');
    }
  }

  /// 解绑Apple账号
  Future<void> unbindApple() async {
    try {} catch (e) {
      print('解绑Apple账号错误: $e');
    }
  }
}

/// 认证结果类
class AuthResult {
  final bool success;
  final Map<String, dynamic>? user;
  final String? provider;
  final String? displayName;
  final String? email;
  final String? error;

  AuthResult({
    required this.success,
    this.user,
    this.provider,
    this.displayName,
    this.email,
    this.error,
  });
}

/// 用户信息类
class UserInfo {
  final String uid;
  final String? email;
  final String? displayName;
  final String? photoURL;
  final String providerId;

  UserInfo({
    required this.uid,
    this.email,
    this.displayName,
    this.photoURL,
    required this.providerId,
  });
}
